import Vue from 'vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import notification from 'ant-design-vue/es/notification'
import {
  ACCESS_TOKEN,
  INDEX_MAIN_PAGE_PATH,
  OAUTH2_LOGIN_PAGE_PATH,
  INTERFACE_PREFIX,
  OAUTH2_LOGIN_PAGE_PATH_EASY_WORK,
  CURRENT_PREFIX,
} from '@/store/mutation-types'
import { generateIndexRouter, isOAuth2AppEnv } from '@/utils/util'
import { login } from '@/utils/login'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/user/login', '/user/register', '/user/register-result', '/uploadLicense'] // no redirect whitelist
const multipageList = ['/ticketsProcessView', '/productionView']
whiteList.push(OAUTH2_LOGIN_PAGE_PATH)
whiteList.push(OAUTH2_LOGIN_PAGE_PATH_EASY_WORK)
router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  let appId = to.meta.appId
  if (appId) {
    let Allprefix = Vue.ls.get(INTERFACE_PREFIX)
    console.log('Allprefix', Allprefix)
    Vue.ls.set(CURRENT_PREFIX, Allprefix[appId], 7 * 24 * 60 * 60 * 1000)
    store.commit('SET_CURRENT_PREFIX', Allprefix[appId])
  } else {
    Vue.ls.set(CURRENT_PREFIX, '', 7 * 24 * 60 * 60 * 1000)
    store.commit('SET_CURRENT_PREFIX', '')
  }

  if (Vue.ls.get(ACCESS_TOKEN)) {
    hasAccessTokenAction(to, from, next)
  } else {
    login()
      .then((data) => {
        if (store.getters.permissionList.length === 0) {
          notPermission(to, from, next)
        } else {
          next()
        }
      })
      .catch((e) => {
        console.log('catch当前的环境是：', sessionStorage.getItem('currentEnvironment'))
        console.log('走的rejectTye类型是：', e.rejectType)
        if (e && e.rejectType == 'browser' && to.path != '/uploadLicense') {
          store.dispatch('Logout').then(() => {
            Vue.ls.remove(ACCESS_TOKEN)
            noAccessTokenAction(to, from, next)
          })
        } else {
          noAccessTokenAction(to, from, next)
        }
      })
    return
  }
})
function hasAccessTokenAction(to, from, next) {
  /* has token */
  if (to.path === '/user/login' || to.path === OAUTH2_LOGIN_PAGE_PATH) {
    next({ path: INDEX_MAIN_PAGE_PATH })
    NProgress.done()
  } else {
    if (store.getters.permissionList.length === 0) {
      notPermission(to, from, next)
    } else {
      if (multipageList.indexOf(to.path) != -1 && to.path != from.path && from.path != '/') {
        let routeUrl = router.resolve({
          path: to.path,
          query: to.query,
          params: to.params,
        })
        window.open(routeUrl.href, '_blank')
        NProgress.done()
        next(false)
      } else {
        next()
      }
    }
  }
}
function noAccessTokenAction(to, from, next) {
  if (whiteList.indexOf(to.path) !== -1) {
    // 在免登录白名单，如果进入的页面是login页面并且当前是OAuth2app环境，就进入OAuth2登录页面
    if (to.path === '/user/login' && isOAuth2AppEnv()) {
      next({ path: OAUTH2_LOGIN_PAGE_PATH })
    } else {
      // 在免登录白名单，直接进入
      next()
    }
    NProgress.done()
  } else {
    // 如果当前是在OAuth2APP环境，就跳转到OAuth2登录页面
    let path = isOAuth2AppEnv() ? OAUTH2_LOGIN_PAGE_PATH : '/user/login'
    next({ path: path })
    NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
  }
}
function notPermission(to, from, next) {
  store
    .dispatch('GetPermissionList')
    .then((res) => {
      const menuData = res.result.menu
      if (menuData === null || menuData === '' || menuData === undefined) {
        return
      }
      let constRoutes = []
      constRoutes = generateIndexRouter(menuData)
      console.log('生成的所有路由：', constRoutes)
      store.dispatch('UpdateAppRouter', { constRoutes }).then(() => {
        router.addRoutes(store.getters.addRouters)
        const redirect = decodeURIComponent(from.query.redirect || to.path)
        if (to.path === redirect) {
          next({ ...to, replace: true })
        } else {
          next({ path: redirect })
        }
      })
    })
    .catch((err) => {
      if (from.path == '/user/login') {
        NProgress.done()
        notification.error({
          message: '登录失败',
          description: err.message,
        })
      }
      store.dispatch('Logout').then(() => {
        next({ path: '/user/login' })
        // next({ path: '/user/login', query: { redirect: to.fullPath } })
      })
    })
}
router.afterEach(() => {
  NProgress.done() // finish progress bar
})

router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g
  const isChunkLoadFailed = error.message.match(pattern)
  const targetPath = router.history.pending.fullPath
  if (isChunkLoadFailed) {
    router.replace(targetPath)
  }
})
